<template>
  <div class="login-container">
    <el-card class="login-card" shadow="hover">
      <div class="login-title">用户登录</div>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            autocomplete="username"
          ></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            autocomplete="current-password"
          ></el-input>
        </el-form-item>

        <el-form-item class="remember-password">
          <el-checkbox v-model="loginForm.remember">记住用户名</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            class="login-button"
            @click="handleLogin"
            :loading="loading"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <div class="register-link">
        还没有账户？<el-button type="text" @click="goToRegister">立即注册</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

// 表单数据
const loginForm = ref({
  username: '',
  password: '',
  remember: false
})

// 表单引用
const loginFormRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)

// 路由
const router = useRouter()

// 用户状态
const userStore = useUserStore()

// 表单验证规则
const loginRules = ref<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
})

// 登录处理
const handleLogin = async () => {
  // 表单验证
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    loading.value = true

    // 调用登录方法
    const result = await userStore.login(loginForm.value)

    if (result.success) {
      ElMessage.success('登录成功')
      await router.push('/')
    } else {
      ElMessage.error(result.message || '登录失败')
    }
  } catch (error: any) {
    if (typeof error === 'string') {
      ElMessage.error(error)
    } else {
      console.error('登录验证失败', error)
    }
  } finally {
    loading.value = false
  }
}

// 页面加载时初始化表单
onMounted(() => {
  // 如果记住了用户名，自动填充
  if (userStore.rememberPassword) {
    loginForm.value.username = userStore.savedUsername
    loginForm.value.remember = true
  }
})

// 跳转到注册页
const goToRegister = () => {
  console.log('点击了注册按钮');
  router.push('/register');
}

</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
  padding: 30px;
}

.login-title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 30px;
  color: #165DFF;
}

.login-form {
  margin-top: 20px;
}

.remember-password {
  display: flex;
  justify-content: flex-end;
}

.login-button {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
}

.register-link {
  text-align: center;
  margin-top: 20px;
  color: #64748B;
}
</style>